package com.study.controller;

import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.demo.trade.config.Configs;
import com.study.common.Const;
import com.study.common.ResponseResult;
import com.study.entity.Order;
import com.study.entity.OrderDetail;
import com.study.entity.PayInfo;
import com.study.service.OrderService;
import com.study.service.PayInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/11/7/007.
 * 订单类
 */
@Controller
@RequestMapping("order")
public class OrderController {
    private Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private OrderService orderService;
    @Autowired
    private PayInfoService payInfoService;

    @RequestMapping("orderList/{uid}")
    public String orderList(@PathVariable Integer uid, Model model) {
        List<Order> orderList = orderService.getOrderList(uid);
        model.addAttribute("orderList", orderList);
        return "orderList";
    }

    @RequestMapping("orderDetailList/{orderId}")
    @ResponseBody
    public ResponseResult orderDetailList(@PathVariable String orderId) {
        List<OrderDetail> orderDetailList = orderService.getOrderDetailList(orderId);
        return new ResponseResult(0, "成功", orderDetailList);
    }

    @RequestMapping("pay/{orderId}/{uid}")
    @ResponseBody
    public ResponseResult pay(@PathVariable String orderId, @PathVariable Integer uid) {
        return orderService.pay(orderId, uid);
    }

    //支付宝回调，解决单边帐问题，只有回调成功才是支付成功，这时才能将支付信息入库
    @RequestMapping("alipay_callback.do")
    @ResponseBody
    public Object callBack(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();

        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        logger.debug("支付宝支付返回参数：" + params);
        params.remove("sign_type");
        try {
            boolean alipayRSACheckedV2 = AlipaySignature.rsaCheckV2(params, Configs.getAlipayPublicKey(), "utf-8", Configs.getSignType());
            if (!alipayRSACheckedV2) {
                throw new RuntimeException("非法请求,验证不通过");
            }
        } catch (Exception e) {
            logger.error("支付宝验证回调异常", e);
            throw new RuntimeException("支付宝验证回调异常");
        }
        //验证通过则修改订单状态，并返回交易信息
        try {
            orderService.aliCallback(params);
            return Const.AlipayCallback.RESPONSE_SUCCESS;//一定要给支付宝返回success，才代表支付成功
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Const.AlipayCallback.RESPONSE_FAILED;

    }

    @RequestMapping("query_order_pay_status/{orderId}")
    @ResponseBody
    public ResponseResult queryOrderPayStatus(@PathVariable String orderId) {
        return orderService.queryOrderPayStatus(orderId)?new ResponseResult(0,"已支付",orderId):new ResponseResult(-1,"未支付",orderId);
    }

    @RequestMapping("getPayInfo/{orderId}")
    public String getPayInfo(@PathVariable String orderId,Model model){
        PayInfo payInfo = payInfoService.findByOrderId(orderId);
        model.addAttribute("payInfo",payInfo);
        return "payResult";
    }
}
